package org.dizena.common.trace.feign.handler;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.dizena.common.base.enums.EnumHeaderKey;
import org.dizena.common.base.enums.EnumLogLevel;
import org.dizena.common.logger.bean.LogInfo;
import org.dizena.common.logger.bean.LogRpcEvent;
import org.dizena.common.trace.feign.FeignTraceAutoProperties;
import org.dizena.common.utils.ReqUtil;
import org.slf4j.MDC;
import org.springframework.context.ApplicationEventPublisher;

import java.util.HashMap;
import java.util.Map;

public class FeignTraceInterceptor implements RequestInterceptor {

    private FeignTraceAutoProperties properties;

    private ApplicationEventPublisher publisher;

    public FeignTraceInterceptor(FeignTraceAutoProperties properties, ApplicationEventPublisher publisher) {
        this.properties = properties;
        this.publisher = publisher;
    }


    @Override
    public void apply(RequestTemplate request) {
        MDC.put(EnumHeaderKey.TRACE_ID.getKey(), ReqUtil.getTrace());
        Map<String, String> addHeader = ReqUtil.filterAllHeaderMap(properties.getKeys());
        addHeader.forEach((k, v) -> request.header(k, v));
        //log.info("feign {} header {}", request.method(), request.headers());
        //logger
        LogInfo logInfo = new LogInfo();
        logInfo.setTraceId(ReqUtil.getTrace());
        logInfo.setClientIp(ReqUtil.getAllHeaderMap().get(EnumHeaderKey.REQUEST_IP));
        logInfo.setRequestTime(System.currentTimeMillis());
        logInfo.setRequestUrl(request.feignTarget().url() + request.url());
        logInfo.setRequestMethod(request.method());
        logInfo.setRequestHeader(new HashMap<>(request.headers()));
        logInfo.setRequestParam(new String(request.body()));
        publisher.publishEvent(new LogRpcEvent(this, logInfo, EnumLogLevel.INFO));
    }


}
